package javase.concurrency;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程
 * 
 * @Package javase
 * @ClassName: LockTest
 * @author Realfighter
 * @date 2014-7-8 下午03:40:19
 */
public class LockTest {

	private final static ReentrantLock lock = new ReentrantLock();

	public static void main(String[] args) {
		new LockThreadByThread().start();
		new Thread(new LockThreadByRunnable()).start();
	}

	/**
	 * 任一线程持有锁时，都会在10次循环执行后才释放锁
	 * 去除lock，输出就比较随意了
	 * @Title: testLock
	 * @author Realfighter
	 * @date 2014-7-9 上午10:56:17
	 * @param name
	 * @param i
	 *            void
	 */
	public static void testLock(String name, int i) {
		lock.lock();
		try {
			for (int j = 0; j < 10; j++) {
				System.out.println(name + " print >>>>>>" + i);
			}
		} catch (Exception e) {
		} finally {
			lock.unlock();
		}
	}

}

class LockThreadByThread extends Thread {
	
	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			LockTest.testLock(Thread.currentThread().getName(), i);
		}
	}
}

class LockThreadByRunnable implements Runnable {
	
	public void run() {
		for (int i = 0; i < 50; i++) {
			LockTest.testLock(Thread.currentThread().getName(), i);
		}
	}
}
